package com.zany.children.action;

import com.zany.children.service.*;
import com.zany.children.vo.*;
import com.zany.children.vo.Class;
import com.zany.system.vo.UserInfoVO;
import com.zany.util.ZanyErrorMsg;
import com.zany.util.ZanyException;
import com.zany.util.action.AbstractActionSupport;
import com.zany.util.ajax.AjaxTools;
import com.zany.util.json.JsonTools;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PaymentOrderAction extends AbstractActionSupport {

    private Map session;
    private ClassService classService;


    private PaymentProjectService paymentProjectService;

    private ChargesOwedService chargesOwedService;

    public ChargesOwedDetailService getChargesOwedDetailService() {
        return chargesOwedDetailService;
    }

    public void setChargesOwedDetailService(ChargesOwedDetailService chargesOwedDetailService) {
        this.chargesOwedDetailService = chargesOwedDetailService;
    }

    private ChargesOwedDetailService chargesOwedDetailService;

    public ChargesOwedService getChargesOwedService() {
        return chargesOwedService;
    }

    public void setChargesOwedService(ChargesOwedService chargesOwedService) {
        this.chargesOwedService = chargesOwedService;
    }

    public PaymentProjectService getPaymentProjectService() {
        return paymentProjectService;
    }

    public void setPaymentProjectService(PaymentProjectService paymentProjectService) {
        this.paymentProjectService = paymentProjectService;
    }


    public StudentService getStudentService() {
        return studentService;
    }

    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    private StudentService studentService;


    public ClassService getClassService() {
        return classService;
    }

    public void setClassService(ClassService classService) {
        this.classService = classService;
    }

    public void list() throws ZanyException {
        String start = request.getParameter("start");
        String name = request.getParameter("name");
        String classId = request.getParameter("classId");
        UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
        response = ServletActionContext.getResponse();
        String pageStart = StringUtils.isBlank(start) ? "1" : start;
        Class clazz = new Class();
        clazz.setName(name);
        if (userInfo != null) {
            clazz.setOrgCode(userInfo.getUserOrg());
        }
        if (StringUtils.isNotBlank(classId)) {
            clazz.setId(Long.parseLong(classId));
        }

        clazz.setPageMessage(Integer.valueOf(pageStart));
        Integer count = classService.getClassListPageCount(clazz);
        List<Class> classListPage = classService.getClassListPage(clazz);
        AjaxTools.exAjax("{results:" + count + ",ZANY:" + JsonTools.lstBeanToJson(classListPage) + "}", response);
    }

    public void update() {

    }


    private void _update(Long classId, JSONObject jsonObject) throws JSONException {
        UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
        String orgCode = userInfo.getUserOrg();
        String creater = userInfo.getUserName();
        Map<String, Object> mapc = new HashMap<String, Object>();
        mapc.put("classId", classId);
        mapc.put("pageStart", 1);
        mapc.put("pageEnd", 100000);
        List<Student> studentListPage = studentService.getStudentListPage(mapc);
        Map<String, Object> condition = new HashMap<String, Object>();
        JSONArray projects = (JSONArray) jsonObject.get("projects");
        ArrayList<String> projectIds = new ArrayList<String>();
        for (int j = 0; j < projects.length(); j++) {
            String projectId = (String) projects.get(j);
            projectIds.add(projectId);
        }
        String symbol = StringUtils.join(projectIds.toArray(), ",");
        condition.put("classId", classId);
        condition.put("projectIds", symbol);
        //查询存在的 ,但修改时并没有选择的都删除.
        List<ChargesOwedDetail> chargesOwedDetailByCondition = chargesOwedDetailService.getChargesOwedDetailByCondition(condition);
        for (ChargesOwedDetail chargesOwedDetail : chargesOwedDetailByCondition) {
            chargesOwedDetailService.deleteChargesOwedDetailById(chargesOwedDetail.getId());
        }
        List<ChargesOwed> chargesOweds = new ArrayList<ChargesOwed>();
        for (Student student : studentListPage) {
            Long studentId = student.getId();
            Double totalMoney = 0.0;
            ChargesOwed chargesOwed = new ChargesOwed();
            chargesOwed.setClassId(classId);
            List<ChargesOwedDetail> chargesOwedDetails = new ArrayList<ChargesOwedDetail>();
            for (int j = 0; j < projects.length(); j++) {
                String projectId = (String) projects.get(j);
                PaymentProject project = paymentProjectService.getPaymentProjectById(Long.parseLong(projectId));
                totalMoney += project.getPreMoney();
                ChargesOwedDetail chargesOwedDetail = new ChargesOwedDetail();
                chargesOwedDetail.setStuId(studentId);
                chargesOwedDetail.setProjectId(Long.parseLong(projectId));
                chargesOwedDetail.setMoney(project.getPreMoney());
                chargesOwedDetail.setChargesType(1);
                chargesOwedDetail.setCreater(creater);
                chargesOwedDetail.setClassId(classId);
                chargesOwedDetails.add(chargesOwedDetail);
            }
            chargesOwed.setChargesOwedDetailList(chargesOwedDetails);
            chargesOwed.setMoney(totalMoney);
            chargesOwed.setOrgCode(orgCode);
            chargesOwed.setCreater(creater);
            chargesOwed.setStuId(studentId);
            chargesOweds.add(chargesOwed);
        }
        chargesOwedService.saveChargesOwedAndDetail(chargesOweds);
    }

    private void _save(Long classId, JSONObject jsonObject) throws JSONException {
        UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
        String orgCode = userInfo.getUserOrg();
        String creater = userInfo.getUserName();
        Map<String, Object> mapc = new HashMap<String, Object>();
        mapc.put("classId", classId);
        mapc.put("pageStart", 1);
        mapc.put("pageEnd", 100000);
        List<Student> studentListPage = studentService.getStudentListPage(mapc);
        List<ChargesOwed> chargesOweds = new ArrayList<ChargesOwed>();
        for (Student student : studentListPage) {
            JSONArray projects = (JSONArray) jsonObject.get("projects");
            Long studentId = student.getId();
            Double totalMoney = 0.0;
            ChargesOwed chargesOwed = new ChargesOwed();
            chargesOwed.setClassId(classId);
            List<ChargesOwedDetail> chargesOwedDetails = new ArrayList<ChargesOwedDetail>();
            for (int j = 0; j < projects.length(); j++) {
                String projectId = (String) projects.get(j);
                PaymentProject project = paymentProjectService.getPaymentProjectById(Long.parseLong(projectId));
                ChargesOwedDetail chargesOwedDetail = new ChargesOwedDetail();
                chargesOwedDetail.setStuId(studentId);
                chargesOwedDetail.setProjectId(Long.parseLong(projectId));
                chargesOwedDetail.setMoney(project.getPreMoney());
                chargesOwedDetail.setChargesType(1);
                chargesOwedDetail.setCreater(creater);
                chargesOwedDetail.setClassId(classId);
                chargesOwedDetails.add(chargesOwedDetail);
            }
            chargesOwed.setChargesOwedDetailList(chargesOwedDetails);
            chargesOwed.setOrgCode(orgCode);
            chargesOwed.setCreater(creater);
            chargesOwed.setStuId(studentId);
            chargesOweds.add(chargesOwed);
        }
        chargesOwedService.saveChargesOwedAndDetail(chargesOweds);
    }


    public void save() throws JSONException, ZanyException {
        try {
            String data = request.getParameter("data");
            UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
            String orgCode = userInfo.getUserOrg();
            response = ServletActionContext.getResponse();
            String creater = userInfo.getUserName();
            org.json.JSONArray jsonArray = new org.json.JSONArray(data); // 传入字符串
            for (int i = 0; i < jsonArray.length(); i++) {
                org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i);
                String classId = (String) jsonObject.get("classid");
                Long classIdL = Long.parseLong(classId);
                Integer count = chargesOwedService.getChargesOwedListPageCount(new ChargesOwed(classIdL));
                if (count == 0)
                    _save(classIdL, jsonObject);
                else
                    _update(classIdL, jsonObject);
            }
            AjaxTools.exAjax("{success:true}", response);
        } catch (Exception e) {
            AjaxTools.exAjax("{success:false}", response);
            throw new ZanyException(ZanyErrorMsg.ERR_DEFAULT, e.getMessage(), e);
        }
    }


    public void delete() {

    }


    public void getProjectByClassId() throws ZanyException {
        response = ServletActionContext.getResponse();
        String classId = request.getParameter("classId");
        List<PaymentProject> projects = chargesOwedService.getOwedPaymentProjectByClassId(Long.parseLong(classId));
        AjaxTools.exAjax("{success:" + true + ",ZANY:" + JsonTools.lstBeanToJson(projects) + "}", response);
    }




    @Override
    public void setSession(Map map) {
        this.session = map;
    }
}
